<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

// 切换登录/注册模式
const isLoginMode = ref(true);

// 根据URL参数设置初始模式
onMounted(() => {
  const mode = route.query.mode;
  if (mode === 'register') {
    isLoginMode.value = false;
  }
});

// 表单状态
interface FormErrors {
  email?: string;
  password?: string;
  confirmPassword?: string;
  username?: string;
  general?: string;
}

const formState = reactive({
  email: '',
  password: '',
  confirmPassword: '',
  username: '',
  errors: {} as FormErrors
});

// 加载状态
const isLoading = ref(false);

// 切换登录/注册
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value;
  // 清空表单和错误
  formState.email = '';
  formState.password = '';
  formState.confirmPassword = '';
  formState.username = '';
  formState.errors = {};
};

// 验证表单
const validateForm = () => {
  formState.errors = {};
  let isValid = true;

  // 邮箱验证
  if (!formState.email.trim()) {
    formState.errors.email = '请输入邮箱';
    isValid = false;
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formState.email)) {
    formState.errors.email = '请输入有效的邮箱地址';
    isValid = false;
  }

  // 密码验证
  if (!formState.password) {
    formState.errors.password = '请输入密码';
    isValid = false;
  } else if (formState.password.length < 6) {
    formState.errors.password = '密码长度至少为6位';
    isValid = false;
  }

  // 注册模式下的额外验证
  if (!isLoginMode.value) {
    // 用户名验证
    if (!formState.username.trim()) {
      formState.errors.username = '请输入用户名';
      isValid = false;
    } else if (formState.username.length < 3) {
      formState.errors.username = '用户名长度至少为3位';
      isValid = false;
    }

    // 确认密码验证
    if (!formState.confirmPassword) {
      formState.errors.confirmPassword = '请确认密码';
      isValid = false;
    } else if (formState.password !== formState.confirmPassword) {
      formState.errors.confirmPassword = '两次输入的密码不一致';
      isValid = false;
    }
  }

  return isValid;
};

// 处理表单提交
const handleSubmit = async () => {
  if (!validateForm()) {
    return;
  }

  isLoading.value = true;

  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 登录或注册成功后的处理
    console.log(isLoginMode.value ? '登录成功' : '注册成功', {
      email: formState.email,
      password: formState.password,
      username: formState.username
    });
    
    // 存储用户信息到本地存储
    localStorage.setItem('user', JSON.stringify({
      email: formState.email,
      username: formState.username || formState.email.split('@')[0]
    }));
    
    // 跳转到首页
    router.push('/');
  } catch (error) {
    console.error('登录或注册失败:', error);
    formState.errors.general = '操作失败，请稍后重试';
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="auth-page">
    <div class="auth-container">
      <div class="auth-header">
        <h1>{{ isLoginMode ? '登录' : '注册' }}</h1>
        <p>{{ isLoginMode ? '欢迎回来，请登录您的账户' : '创建新账户，开始使用我们的服务' }}</p>
      </div>
      
      <div v-if="formState.errors.general" class="error-message general-error">
        {{ formState.errors.general }}
      </div>
      
      <form @submit.prevent="handleSubmit" class="auth-form">
        <!-- 用户名输入框 (仅注册模式显示) -->
        <div v-if="!isLoginMode" class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="formState.username"
            placeholder="请输入用户名"
            :class="{ 'error': formState.errors.username }"
          />
          <div v-if="formState.errors.username" class="error-message">
            {{ formState.errors.username }}
          </div>
        </div>
        
        <!-- 邮箱输入框 -->
        <div class="form-group">
          <label for="email">邮箱</label>
          <input
            type="email"
            id="email"
            v-model="formState.email"
            placeholder="请输入邮箱"
            :class="{ 'error': formState.errors.email }"
          />
          <div v-if="formState.errors.email" class="error-message">
            {{ formState.errors.email }}
          </div>
        </div>
        
        <!-- 密码输入框 -->
        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="formState.password"
            placeholder="请输入密码"
            :class="{ 'error': formState.errors.password }"
          />
          <div v-if="formState.errors.password" class="error-message">
            {{ formState.errors.password }}
          </div>
        </div>
        
        <!-- 确认密码输入框 (仅注册模式显示) -->
        <div v-if="!isLoginMode" class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            type="password"
            id="confirmPassword"
            v-model="formState.confirmPassword"
            placeholder="请再次输入密码"
            :class="{ 'error': formState.errors.confirmPassword }"
          />
          <div v-if="formState.errors.confirmPassword" class="error-message">
            {{ formState.errors.confirmPassword }}
          </div>
        </div>
        
        <!-- 提交按钮 -->
        <button type="submit" class="submit-button" :disabled="isLoading">
          {{ isLoading ? (isLoginMode ? '登录中...' : '注册中...') : (isLoginMode ? '登录' : '注册') }}
        </button>
      </form>
      
      <!-- 切换登录/注册 -->
      <div class="auth-toggle">
        <p>
          {{ isLoginMode ? '还没有账户？' : '已有账户？' }}
          <button type="button" class="toggle-button" @click="toggleMode">
            {{ isLoginMode ? '立即注册' : '立即登录' }}
          </button>
        </p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.auth-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 120px); /* 减去导航栏和页脚的高度 */
  padding: 2rem 0;
  background-color: #f5f5f5;
}

.auth-container {
  width: 100%;
  max-width: 450px;
  background-color: white;
  border-radius: 12px;
  padding: 2.5rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.auth-header {
  text-align: center;
  margin-bottom: 2rem;
}

.auth-header h1 {
  color: #1a1a1a;
  font-size: 2.2rem;
  margin: 0 0 0.5rem 0;
}

.auth-header p {
  color: #666;
  font-size: 1.1rem;
  margin: 0;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #1a1a1a;
  font-weight: bold;
  font-size: 0.9rem;
}

.form-group input {
  width: 100%;
  padding: 0.875rem 1rem;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #00ccff;
  box-shadow: 0 0 0 3px rgba(0, 204, 255, 0.1);
}

.form-group input.error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 0.875rem;
  margin-top: 0.25rem;
}

.general-error {
  text-align: center;
  margin-bottom: 1.5rem;
  padding: 0.75rem;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
}

.submit-button {
  width: 100%;
  padding: 1rem;
  background-color: #00ccff;
  color: #1a1a1a;
  border: none;
  border-radius: 6px;
  font-size: 1.1rem;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
}

.submit-button:hover:not(:disabled) {
  background-color: #00a3cc;
  transform: translateY(-2px);
}

.submit-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.auth-toggle {
  text-align: center;
  margin-top: 1.5rem;
}

.auth-toggle p {
  color: #666;
  margin: 0;
}

.toggle-button {
  background: none;
  border: none;
  color: #00ccff;
  font-weight: bold;
  cursor: pointer;
  padding: 0;
  font-size: 1rem;
  transition: color 0.3s ease;
}

.toggle-button:hover {
  color: #00a3cc;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-container {
    margin: 0 1.5rem;
    padding: 2rem;
  }
  
  .auth-header h1 {
    font-size: 1.8rem;
  }
}
</style>